package com.block.datapush.form.item;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.service.LogFactory;
import com.block.datapush.form.service.IFormPushHandle;
import com.block.datapush.form.item.util.YiXinHuaUtil;
import com.block.datapush.model.dto.FormPushResultDTO;
import com.block.db.entity.FormInfo;
import com.block.db.entity.FormInfoHis;
import com.block.db.entity.MemberExtInfo;
import org.slf4j.Logger;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 亿信花
 */
@Service
public class YiXinHuaPushHandleService implements IFormPushHandle {

    private static final Logger log = LogFactory.getCommLog();

    @Override
    public boolean queryMatchResult(FormInfo formInfo, MemberExtInfo memberExtInfo) {
        try {

            String queryUrl = StrUtil.format(formInfo.getQueryUrl(), formInfo.getApiKey());
            String mobileMd5 = SecureUtil.md5(memberExtInfo.getMobile()).toLowerCase();
            String idCardMd5 = SecureUtil.md5(memberExtInfo.getIdCard()).toLowerCase();
            String city = StrUtil.format("{}/{}", memberExtInfo.getProvince(), memberExtInfo.getCity());

            Map<String, Object> bizParam = new HashMap<>();
            bizParam.put("idno_md5", idCardMd5);
            bizParam.put("phone_md5", mobileMd5);
            bizParam.put("city", city);

            String data = YiXinHuaUtil.encrypt(JSON.toJSONString(bizParam), formInfo.getApiSecret());

            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("data", data);

            log.info("【亿信花】撞库开始【queryUrl】{}【bizParam】{}【paramMap】{}",
                    queryUrl, JSON.toJSONString(bizParam), JSON.toJSONString(paramMap));
            String result = HttpUtil.createPost(queryUrl)
                    .header("Content-Type", "application/json")
                    .body(JSON.toJSONString(paramMap))
                    .execute().body();
            log.info("【亿信花】撞库结束【result】{}", result);

            JSONObject resultObject = JSON.parseObject(result);
            Integer code = resultObject.getInteger("code");
            String msg = resultObject.getString("msg");

            if (ObjectUtil.equal(code, Integer.valueOf(0))){
                return true;
            }
            return false;
        }catch (Exception exception){
            exception.printStackTrace();
        }
        return false;
    }

    @Override
    public FormPushResultDTO pushMemberInfo(FormInfo formInfo, MemberExtInfo memberExtInfo, String orderNo, JSONObject extObject) {
        FormPushResultDTO pushResultDTO = new FormPushResultDTO();
        pushResultDTO.setOrderNo(orderNo);
        try {

            String requestUrl = StrUtil.format(formInfo.getRequestUrl(), formInfo.getApiKey());

            Map<String, Object> bizParam = new HashMap<>();
            bizParam.put("name", memberExtInfo.getUsername());
            bizParam.put("idno", memberExtInfo.getIdCard());
            bizParam.put("phone", memberExtInfo.getMobile());
            bizParam.put("ip", memberExtInfo.getReqIp());
            bizParam.put("working_city", StrUtil.format("{}/{}", memberExtInfo.getProvince(), memberExtInfo.getCity()));

            bizParam.put("zhima", YiXinHuaUtil.getZhima(memberExtInfo.getZhimaScore()));// 芝麻分值(350-950)，具体分值
            bizParam.put("car", YiXinHuaUtil.getCar(memberExtInfo.getCar()));// 车产信息：有车（全款）,有车（按揭已结清）,有车（按揭中）,无车
            bizParam.put("real_estate", YiXinHuaUtil.getHouse(memberExtInfo.getHouse()));// 房产信息：有房（红本在手）,有房（住房按揭中）,有房（抵押中）,无房
            bizParam.put("insurance", YiXinHuaUtil.getBaodan(memberExtInfo.getInsurance()));// 投保信息：投保两年以上、投保两年以下、无
            bizParam.put("credit_record", YiXinHuaUtil.getYuqi(memberExtInfo.getYuqi()));// 信用记录：一年内有逾期、一年内无逾期、无贷款、无逾期、逾期超过90天、逾期少于90天
            bizParam.put("credit_card", "1万-3万");// 信用卡：1万以下、1万-3万、3万以上、无信用卡
            bizParam.put("reserved_funds", YiXinHuaUtil.getGjj(memberExtInfo.getGjj()));// 公积金：6个月以上、6个月以下、无公积金
            bizParam.put("social_security", YiXinHuaUtil.getShebao(memberExtInfo.getSocialInsurance()));// 社保：6个月以上、6个月以下、无社保
            bizParam.put("loan_amount", YiXinHuaUtil.getLoamAmount(memberExtInfo.getLoanAmount()));// 贷款额度：1万-1000万 以万浮动
            bizParam.put("loan_period", YiXinHuaUtil.getLoanTime(memberExtInfo.getLoanTime()));// 贷款期限：1个月-480个月

            bizParam.put("revenue", "8000");//个人收入（月收入）：范围 1000-30000 整千浮动 最低：1000及以下， 最高 ：30000及以上 ，例如 4000
            bizParam.put("salary_type", "银行代发");//收入形式：银行代发、现金发放、个人转账
            bizParam.put("seniority", "在职6个月以上");// 单位工龄：在职6个月以上、在职6个月以下、待业中
            bizParam.put("education", "大专");// 学历：研究生及以上、本科、大专、高中及以下
            bizParam.put("loan_purpose", "消费");// 贷款用途：教育培训、消费、结婚、购房、购车、装修
            bizParam.put("industry", "上班族");// 职业：上班族、公务员/国企/事业单位、企业主、个体户、自由职业、待业
            bizParam.put("loan_lately", "申请3次以内");// 最近（30天内）贷款情况：没有申请过贷款、申请3次以内、申请3-5次、申请5次以上

            String data = YiXinHuaUtil.encrypt(JSON.toJSONString(bizParam), formInfo.getApiSecret());

            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("data", data);

            log.info("【亿信花】导单开始【requestUrl】{}【bizParam】{}【paramMap】{}",
                    requestUrl, JSON.toJSONString(bizParam), JSON.toJSONString(paramMap));
            String result = HttpUtil.createPost(requestUrl)
                    .header("Content-Type", "application/json")
                    .body(JSON.toJSONString(paramMap))
                    .execute().body();
            log.info("【亿信花】导单结束【result】{}", result);

            JSONObject resultObject = JSON.parseObject(result);

            Integer code = resultObject.getInteger("code");
            String msg = resultObject.getString("msg");

            pushResultDTO.setResult(result);
            pushResultDTO.setCode(String.valueOf(code));
            pushResultDTO.setMessage(msg);
            pushResultDTO.setParamContent(JSON.toJSONString(paramMap));
            if (ObjectUtil.equal(code, Integer.valueOf(0))){
                String tid = resultObject.getString("tid");
                pushResultDTO.setSuccess(true);
                pushResultDTO.setOutOrderNo(tid);
            }else{
                pushResultDTO.setSuccess(false);
            }
            return pushResultDTO;
        }catch (Exception exception){
            exception.printStackTrace();
        }
        return pushResultDTO;
    }

    @Override
    public void afterPushHandle(FormInfoHis formInfoHis) {

    }
}
